//
//  EFengMineAttentionController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/3/3.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "EFengMineAttentionController.h"
#import "CFolderMgr.h"
#import "CContactMgr.h"
#import "EFengShareButton.h"
#import "CMineAttentionContact.h"
#import "CAttentionMgr.h"
#import "CXmppRequestMgr.h"
#import "MBProgressHUD+WZ.h"
#import "GroupMenberCell.h"
#import "CContactModel.h"
#import "UIImageView+WebCache.h"
#import "CHChatRoomBase.h"
#import "EFengPersonalShareController.h"

@interface EFengMineAttentionController ()<UITableViewDataSource, UITableViewDelegate>

StrongProperty CContactModel *curContact;
StrongProperty CContactMgr *conMgr;
WeakProperty UIView *topView;
StrongProperty NSArray *dataArray;
WeakProperty EFengShareButton *selectedButton;
//bug 9519 fixed by lixu 显示这里暂时空空
@property(nonatomic,weak)UILabel *noticeLable;
StrongProperty UITableView *tableView;
StrongProperty CAttentionMgr *attentionMgr;
WeakProperty UILabel *countLabel;

@end

@implementation EFengMineAttentionController

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = ClearColor;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IsIOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationItem setNewTitleCenter:@"我的关注"];

    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    
    UILabel *label = [[UILabel alloc] init];
    label.backgroundColor = ClearColor;
    label.textAlignment = NSTextAlignmentCenter;
    label.font = Font16;
    label.textColor = RGBCOLORWITH16COLOR(0xb1b1b1);
    label.text = @"这里暂时空空的～";
    label.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, Font16.lineHeight);
    label.center = self.view.center;
    [self.view addSubview:label];
    self.noticeLable = label;
    self.conMgr = [[CContactMgr alloc] init];
    self.attentionMgr = [[CAttentionMgr alloc] init];
    self.curContact = [self.conMgr loadCurContact];
    
    [self setupTopView];
    
    self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.topView.frame), HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64.0f - CGRectGetMaxY(self.topView.frame));
    [self.view addSubview:self.tableView];
    
    [self loadData];

}

- (void)setupTopView
{
    UIView *topView = [[UIView alloc] init];
    topView.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, 70.0f);
    topView.backgroundColor = ClearColor;
    [self.view addSubview:topView];
    self.topView = topView;
    
   EFengShareButton *quanbu = [EFengShareButton buttonwithCorners:UIRectCornerBottomLeft | UIRectCornerTopLeft selectedColor:RGBCOLORWITH16COLOR(0xd4d4d4) normalColor:WhiteColor];
    quanbu.tag = 50001;
    quanbu.frame = CGRectMake((HARDWARE_SCREEN_WIDTH - 200.0f) / 2.0f, 5.0f, 100.0f, 40.0f);
    [quanbu addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [quanbu setTitleColor:BlackColor forState:UIControlStateNormal];
    [quanbu setTitle:@"我关注的人" forState:UIControlStateNormal];
    quanbu.titleLabel.font = Font16;
    [topView addSubview:quanbu];
    
    
    [self buttonClick:quanbu];
    //默认查看全部分享
    
    
    EFengShareButton *mineAttention = [EFengShareButton buttonwithCorners:UIRectCornerBottomRight | UIRectCornerTopRight selectedColor:RGBCOLORWITH16COLOR(0xd4d4d4) normalColor:WhiteColor];
    mineAttention.tag = 50002;
    mineAttention.frame = CGRectMake(CGRectGetMaxX(quanbu.frame), 5.0f, 100.0f, 40.0f);
    [mineAttention addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [mineAttention setTitleColor:BlackColor forState:UIControlStateNormal];
    [mineAttention setTitle:@"关注我的人" forState:UIControlStateNormal];
    mineAttention.titleLabel.font = Font16;
    [topView addSubview:mineAttention];
    
    
    UILabel *countLabel = [[UILabel alloc] init];
    countLabel.frame = CGRectMake(CGRectGetMaxX(mineAttention.frame) + 10.0f, 45.0f, HARDWARE_SCREEN_WIDTH - CGRectGetMaxX(mineAttention.frame) - 20.0f, 20.0f);
    countLabel.font = Font14;
    countLabel.textColor = RGBCOLORWITH16COLOR(0x323232);
    countLabel.textAlignment = UITextAlignmentLeft;
    [topView addSubview:countLabel];
    self.countLabel = countLabel;
    
}

- (void)buttonClick:(EFengShareButton *)btn
{
    self.selectedButton.selected = NO;
    btn.selected = YES;
    self.selectedButton = btn;
    switch (btn.tag) {
        case 50001:
        {
            NSMutableArray *arrayM = [NSMutableArray array];
            NSArray *array = [self.attentionMgr loadAttentionContactsWithIsAttentionMe:NO];
            for (CMineAttentionContact *model in array) {
                CContactModel *contact = [_conMgr loadNotDelContactWithUserId:model.userId];
                if (contact) {
                    contact.yuLiuZiduan3 = @"";
                    [arrayM addObject:contact];
                }
            }
            self.dataArray = [arrayM sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"PinYin" ascending:YES]]];
            if (self.dataArray.count > 0) {
                self.countLabel.text = [NSString stringWithFormat:@"共%zd人",self.dataArray.count];
            } else {
                self.countLabel.text = @"";
            }
            
            [self.tableView reloadData];
            
        }
            break;
        case 50002:
        {
            NSMutableArray *arrayM = [NSMutableArray array];
            NSArray *array = [self.attentionMgr loadAttentionContactsWithIsAttentionMe:YES];
            for (CMineAttentionContact *model in array) {
                CContactModel *contact = [_conMgr loadNotDelContactWithUserId:model.userId];
                if (contact) {
                    contact.yuLiuZiduan3 = @"";
                    [arrayM addObject:contact];
                }
            }
            self.dataArray = [arrayM sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"PinYin" ascending:YES]]];
            if (self.dataArray.count > 0) {
                self.countLabel.text = [NSString stringWithFormat:@"共%zd人",self.dataArray.count];
            } else {
                self.countLabel.text = @"";
            }

            [self.tableView reloadData];

        }
            break;
  
        default:
            break;
    }
}

- (void)loadData
{
    [MBProgressHUD showMessage:@"加载中，请稍候..." toView:self.view];
    [[CXmppRequestMgr shareInstance] getMineAttentionWithsuccessHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        NSString *result = responseObject[@"result"];
        if ([result isEqualToString:@"success"]) {
            [self.attentionMgr delAllAttentionContacts];
            
            NSMutableArray *arrayM = [NSMutableArray array];
            NSString *meAttentionId = responseObject[@"meAttentionId"];
            NSArray *meAttentionIdArray = [meAttentionId componentsSeparatedByString:@","];
            [meAttentionIdArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                CMineAttentionContact *attention = [[CMineAttentionContact alloc] init];
                attention.userId = obj;
                attention.isAttentionMe = NO;
                [arrayM addObject:attention];
            }];
            
            NSString *attentionMeId = responseObject[@"attentionMeId"];
            NSArray *attentionMeIdArray = [attentionMeId componentsSeparatedByString:@","];
            [attentionMeIdArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
                CMineAttentionContact *attention = [[CMineAttentionContact alloc] init];
                attention.userId = obj;
                attention.isAttentionMe = YES;
                [arrayM addObject:attention];
            }];
            
            [self.attentionMgr batchInsertAttentionContact:arrayM];
            [self buttonClick:self.selectedButton];
        }
    } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"加载失败" toView:self.view];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.dataArray.count > 0) {
        self.noticeLable.hidden = YES;
    }
    else
    {
        self.noticeLable.hidden = NO;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.0f;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 0.01f;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section   // custom view for footer. will be adjusted to default or specified footer height
{
    return nil;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (self.selectedButton.tag) {
        case 50001:
        {
            return UITableViewCellEditingStyleDelete;
        }
            break;
        default:
        {
            return UITableViewCellEditingStyleNone;
        }
            break;
    }
    
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    CContactModel *contact = self.dataArray[indexPath.row];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [[CXmppRequestMgr shareInstance] cancelMineAttentionWithUserId:contact.UserID successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([responseObject[@"result"] isEqualToString:@"success"]) {
                [self.attentionMgr delAttentionContact:contact.UserID];
                [[NSNotificationCenter defaultCenter] postNotificationName:IMDIDUPDATEMINEATTENTION object:nil];
                [self buttonClick:self.selectedButton];
            }
        } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            
        }];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
    
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (self.selectedButton.tag) {
        case 50001:
        {
            return YES;
        }
        default:
        {
            return NO;
        }
            break;
    }
    
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0)
{
    return @"取消关注";
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CContactModel *contact = self.dataArray[indexPath.row];
    UITableViewCell *cell = nil;
    
    static NSString *NormalCellIdentifier = @"GroupMenberCell";
    GroupMenberCell *groupMemberCell = [tableView dequeueReusableCellWithIdentifier:NormalCellIdentifier];
    if (groupMemberCell == nil) {
        groupMemberCell = [[[NSBundle mainBundle] loadNibNamed:@"GroupMenberCell" owner:self options:nil] objectAtIndex:0];
    }
    if ([contact.yuLiuZiduan3 isEqualToString:@"isKefu"]) {
        [groupMemberCell.icon setImage:[UIImage imageNamed:@"head-kefu"]];
    } else {
        [groupMemberCell.icon sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:contact.UserID]] placeholderImage:[UIImage imageNamed:@"80-80"]];
    }
    
    //        [groupMemberCell.titleLabel setText:@"测试名字"];
    [groupMemberCell.titleLabel setText:contact.UserName];
    groupMemberCell.Arrow.hidden = NO;
    NSInteger rows = [tableView numberOfRowsInSection:indexPath.section];
    if(indexPath.row == rows - 1)
    {
        [groupMemberCell.seperatorLine setHidden:YES];
    } else {
        groupMemberCell.seperatorLine.hidden = NO;
    }
    cell = groupMemberCell;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
    CContactModel *contact = self.dataArray[indexPath.row];
    
    
    if (!M_ISSTRNULL(contact.UserID)) {
        EFengPersonalShareController *per = [[EFengPersonalShareController alloc] init];
        per.userId = contact.UserID;
        [self.navigationController pushViewController:per animated:YES];
    }
}



@end
